package com.sentinel.datasource;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义规则加载的数据源
 */
public class MyDatasource implements InitFunc {
    @Override
    public void init() throws Exception {
        String file=null;
        //获取文件的全路径名称
        ClassLoader classLoader = MyDatasource.class.getClassLoader();
        URL resource = classLoader.getResource("flowRules.json");//会从类加载路径根(classpath 就是输出classes文件夹)
        file=resource.getFile();//文件全路径
        //读取 json文本 flowRules.json
        FileRefreshableDataSource dataSource=
                new FileRefreshableDataSource(file, new Converter() {
                    @Override
                    public Object convert(Object json) {
                        //o就是文本内容
                        String jsonStr=(String)json;
                        //返回值就是规则数据对象List<FlowRule>
                        List<FlowRule> flowRules = JSON.parseArray(jsonStr, FlowRule.class);
                        return flowRules;
                    }
                });
        //需要将这个datasource注册到sentinel
        FlowRuleManager.register2Property(dataSource.getProperty());
        System.out.println("sentinel规则加载完毕");
    }
}
